var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var scene;
(function (scene) {
    var PKMatchScene = /** @class */ (function (_super) {
        __extends(PKMatchScene, _super);
        function PKMatchScene() {
            var _this = _super.call(this) || this;
            _this.isConnected = false;
            _this.roomId = "";
            _this.startBtnP = new egret.Point();
            _this.inviteBtnP = new egret.Point();
            _this.userInfoList = new Array();
            _this.playTimes = 0;
            _this.isJoin = false;
            _this.isGameStarted = false;
            _this.addEventListener(eui.UIEvent.COMPLETE, _this.onComplete, _this);
            _this.skinName = "resource/assets/GameRes/game/skins/PKMatchSceneSkin.exml";
            return _this;
        }
        PKMatchScene.prototype.update = function (data) {
            this.reset();
            manager.DisplayManager.remove(this.pkFinishScene);
            manager.DisplayManager.remove(this.pkGameScene);
            this.setInfo(data.isJoin, data.roomId);
            this.start();
        };
        PKMatchScene.prototype.reset = function () {
            this.userInfoList = [];
            this.playTimes = 0;
            this.isJoin = false;
            this.isGameStarted = false;
            this.updateData();
        };
        PKMatchScene.prototype.onComplete = function (eve) {
            this.bgImg.width = manager.DisplayManager.STAGE_WIDTH;
            this.bgImg.height = manager.DisplayManager.STAGE_HEIGHT;
            var dataGroup = this.userInfoListDataGroup;
            dataGroup.itemRenderer = HouseMemberItemRender;
            dataGroup.useVirtualLayout = true;
            dataGroup.scrollEnabled = true;
            var tLayout = new eui.TileLayout();
            tLayout.requestedRowCount = 2;
            tLayout.requestedColumnCount = 1;
            tLayout.verticalGap = 23;
            tLayout.horizontalGap = 23;
            dataGroup.layout = tLayout;
            this.scroller.viewport = dataGroup;
            this.scroller.width = dataGroup.width;
            var btn = new ui.PushButton(this.btnBackImg);
            btn.addEventListener(ui.PushButton.CLICK, this.onBacked, this);
            this.rootGroup.addChild(btn);
            this.btnPlay = new ui.PushButton(this.btnPlayImg);
            this.btnPlay.addEventListener(ui.PushButton.CLICK, this.onPlay, this);
            this.bottomGroup.addChild(this.btnPlay);
            this.btnInvite = new ui.PushButton(this.btnInviteImg);
            this.btnInvite.addEventListener(ui.PushButton.CLICK, this.onInviteClicked, this);
            this.bottomGroup.addChild(this.btnInvite);
            this.startBtnP.x = this.btnPlay.x;
            this.startBtnP.y = this.btnPlay.y;
            this.inviteBtnP.x = this.btnInvite.x;
            this.inviteBtnP.y = this.btnInvite.y;
            this.updateData();
        };
        PKMatchScene.prototype.setInfo = function (isJoin, roomId) {
            this.isJoin = isJoin;
            this.roomId = roomId;
            this.btnPlay.visible = true;
            this.btnInvite.visible = true;
            this.btnInvite.x = this.inviteBtnP.x;
            this.btnInvite.y = this.inviteBtnP.y;
            if (this.isJoin) {
                this.btnInvite.visible = false;
                this.btnPlay.visible = false;
                this.btnInvite.x = this.bottomGroup.width - this.btnPlayImg.width >> 1;
            }
        };
        PKMatchScene.prototype.start = function () {
            var that = this;
            if (this.pomelo != null) {
                this.pomelo.disconnect();
            }
            this.pomelo = new PomeloForEgret.Pomelo();
            this.pomelo.on(PomeloForEgret.Pomelo.EVENT_IO_ERROR, function (event) {
                console.error("error", event);
            });
            this.pomelo.on("joinRoomNotify", function (event) {
                console.error("joinRoomNotify:", event);
                that.addUser(event.userInfo);
            });
            this.pomelo.on("leaveRoomNotify", function (event) {
                console.error("leaveRoomNotify:", event);
                that.removeUser(event.userInfo);
            });
            this.pomelo.on("onGameReady", function (event) {
                console.error("onGameReady:", event);
                that.setReady();
            });
            this.pomelo.on("onGameStart", function (event) {
                console.error("onGameStart:", event);
                that.sendSelectLevelCommand();
            });
            //
            // this.pomelo.on("onGameOver", function (event) {
            //     that.onGameOver(event);
            // });
            this.pomelo.on("game.gameHandler.sendEvent", function (event) {
                console.error("game.gameHandler.sendEvent:", event);
                that.handleCustomMessage(event);
            });
            this.pomelo.on("userInput", function (event) {
                that.handleCustomMessage(event);
            });
            this.pomelo.init({
                host: PKMatchScene.ROUTE_SERVER_HOST,
                port: PKMatchScene.ROUTE_SERVER_PORT,
            }, function () {
                that.pomelo.request('gate.gateHandler.queryEntry', {}, function (data) {
                    that.pomelo.disconnect();
                    if (data.code !== 200) {
                        throw new Error('请求游戏服务器地址出错');
                    }
                    var host = data.host, port = data.port;
                    that.connect(host, port);
                });
            });
        };
        PKMatchScene.prototype.handleCustomMessage = function (data) {
            egret.log("处理自定义消息:", data);
            data = data.data;
            if (data.command == PKMatchScene.SELECT_LEVEL_COMMAND) {
                this.level = data.level;
                this.onGameStart();
            }
            else if (data.command == PKMatchScene.SYNC_WIN_SCORE) {
                var wechatId = data.wechatId;
                this.setWiner(wechatId, data.seconds);
                this.showFinishScene();
            }
            else if (data.command == PKMatchScene.REPLAY_GAME) {
                this.replay();
            }
            else if (data.command == PKMatchScene.LEAVE_ROOM) {
                this.onRoleLeaveRoom(data.wechatId);
                egret.log("PKMatchScene.LEAVE_ROOM:", PKMatchScene.LEAVE_ROOM);
                if (this.roomInfo.ownerId == data.wechatId) {
                    egret.log("重新创建房间");
                    this.showRoomMasterLeave();
                }
            }
        };
        PKMatchScene.prototype.showRoomMasterLeave = function () {
            var page = new scene.PkMasterLeaveScene();
            this.addChild(page);
        };
        PKMatchScene.prototype.onRoleLeaveRoom = function (wechatId) {
            for (var i = 0; i < this.userInfoList.length; i++) {
                var roleInfo = this.userInfoList[i];
                if (roleInfo.wechatId == wechatId) {
                    roleInfo.isReady = false;
                }
            }
            this.updateData();
        };
        PKMatchScene.prototype.replay = function () {
            manager.DisplayManager.remove(this.pkGameScene);
            manager.DisplayManager.remove(this.pkFinishScene);
        };
        PKMatchScene.prototype.showFinishScene = function () {
            if (this.pkFinishScene == null) {
                this.pkFinishScene = new scene.PKGameFinishScene();
            }
            this.hideChildScene();
            this.pkFinishScene.addEventListener(PKGameFinishScene.REPLAY, this.onRelayClicked, this);
            this.addChild(this.pkFinishScene);
            this.pkFinishScene.update(this.userInfoList);
        };
        PKMatchScene.prototype.hideChildScene = function () {
            manager.DisplayManager.remove(this.pkGameScene);
            manager.DisplayManager.remove(this.pkFinishScene);
        };
        PKMatchScene.prototype.onRelayClicked = function (eve) {
            this.sendReplayCommand();
            this.replay();
        };
        PKMatchScene.prototype.sendReplayCommand = function () {
            var level = manager.RandomManager.getRandRange(6, 10);
            this.level = level;
            this.sendCustomMessage({
                command: PKMatchScene.REPLAY_GAME,
                level: level
            });
        };
        PKMatchScene.prototype.sendCustomMessage = function (msgData) {
            var param = {
                msgType: "userInput",
                msgData: msgData
            };
            this.pomelo.request('game.gameHandler.sendEvent', param, function (resp) {
                console.log(resp);
            });
        };
        PKMatchScene.prototype.onGameOver = function (data) {
            egret.log("PK结束:", data);
            if (this.pkGameScene != null) {
                this.pkGameScene.stop();
            }
        };
        PKMatchScene.prototype.updateRoom = function () {
            var len = this.userInfoList.length;
            for (var i = 0; i < len; i++) {
                var user = this.userInfoList[i];
                user.isOwner = false;
                if (this.roomInfo.ownerId == user.wechatId) {
                    this.txtHouse.text = user.wechatName + "的房间";
                    user.isOwner = true;
                }
            }
        };
        PKMatchScene.prototype.onInviteClicked = function (eve) {
            if (this.playTimes > 0 && this.getReadyUserCount() < 2) {
                egret.log("重新创建房间");
                this.recreateRoom();
                return;
            }
            this.inviteFriend();
        };
        PKMatchScene.prototype.inviteFriend = function () {
            var info = manager.GameManager.getInstance().adManager.getShareInfo();
            manager.GameManager.getInstance().share(info.title, info.img, null, manager.LaunchOptionsManager.ROOM_ID + "=" + this.roomInfo.roomId);
        };
        //重新创建房间
        PKMatchScene.prototype.recreateRoom = function () {
            egret.log("重新创建房间");
            var that = this;
            this.reset();
            wx.showModal({
                title: '提示',
                content: '房间已失效，可重新创建创建房间',
                confirmText: "创建房间",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        that.start();
                    }
                    else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        };
        PKMatchScene.prototype.getReadyUserCount = function () {
            var len = this.userInfoList.length;
            var readyUserCount = 0;
            for (var i = 0; i < len; i++) {
                if (this.userInfoList[i].isReady) {
                    readyUserCount++;
                }
            }
            return readyUserCount;
        };
        PKMatchScene.prototype.onPlay = function (eve) {
            if (this.isJoin) {
                return;
            }
            if (this.playTimes > 0 && this.getReadyUserCount() < 2) {
                egret.log("重新创建房间");
                this.recreateRoom();
                return;
            }
            var that = this;
            if (this.getReadyUserCount() < 2) {
                wx.showModal({
                    title: '提示',
                    content: '房间未满两人，不能开始',
                    confirmText: "邀请好友",
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            that.inviteFriend();
                        }
                        else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
                return;
            }
            if (this.isGameStarted) {
                this.sendSelectLevelCommand();
            }
            else {
                this.sendStartCommand();
                this.isGameStarted = true;
            }
        };
        PKMatchScene.prototype.sendSelectLevelCommand = function () {
            if (this.isJoin) {
                return;
            }
            // let level: number = manager.RandomManager.getRandRange(50, 500);
            var level = manager.RandomManager.getRandRange(6, 10);
            this.level = level;
            this.sendCustomMessage({
                command: PKMatchScene.SELECT_LEVEL_COMMAND,
                level: level
            });
            this.onGameStart();
        };
        PKMatchScene.prototype.sendStartCommand = function () {
            this.pomelo.request("match.matchHandler.startGame", {}, function (data) {
                egret.log("");
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
        };
        PKMatchScene.prototype.onGameStart = function () {
            if (this.pkGameScene == null) {
                this.pkGameScene = new PkGameScene();
            }
            this.playTimes++;
            var readyRoleInfos = [];
            for (var i = 0; i < this.userInfoList.length; i++) {
                var roleInfo = this.userInfoList[i];
                if (roleInfo.isReady) {
                    readyRoleInfos.push(roleInfo);
                }
            }
            this.pkGameScene.setMembers(readyRoleInfos);
            this.addChild(this.pkGameScene);
            this.pkGameScene.setLevel(this.level);
            this.pkGameScene.addEventListener(scene.PkGameScene.PK_FINISH, this.onPkFinish, this);
        };
        PKMatchScene.prototype.onPkFinish = function (eve) {
            this.costSeconds = eve.data;
            this.win();
        };
        PKMatchScene.prototype.win = function () {
            var openId = manager.GameManager.getInstance().openid;
            this.sendCustomMessage({
                "seconds": this.costSeconds,
                "command": scene.PKMatchScene.SYNC_WIN_SCORE,
                "wechatId": manager.GameManager.getInstance().openid,
            });
            this.setWiner(openId, this.costSeconds);
            this.showFinishScene();
        };
        PKMatchScene.prototype.updateData = function () {
            this.userInfoListDataGroup.dataProvider = new eui.ArrayCollection(this.userInfoList);
            this.updateRoom();
        };
        PKMatchScene.prototype.onBacked = function (eve) {
            var that = this;
            if (this.isJoin) {
                wx.showModal({
                    title: '提示',
                    content: '退出对战后,只能通过原来的分享链接进入',
                    confirmText: "退出",
                    success: function (res) {
                        if (res.confirm) {
                            that.exit();
                        }
                        else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
            }
            else {
                wx.showModal({
                    title: '提示',
                    content: '关闭房间，其余玩家也将退出游戏',
                    confirmText: "退出",
                    success: function (res) {
                        if (res.confirm) {
                            that.exit();
                        }
                        else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
            }
            this.isJoin = false;
            this.isGameStarted = false;
            this.isConnected = false;
        };
        PKMatchScene.prototype.exit = function () {
            this.leaveRoom();
            var event = new events.SceneEvent(game.SceneIds.START_SCENE_ID, {});
            facade.GameFacade.getInstance().dispatchEvent(event);
        };
        PKMatchScene.prototype.createChildren = function () {
            _super.prototype.createChildren.call(this);
        };
        PKMatchScene.prototype.setWiner = function (wechatId, seconds) {
            var len = this.userInfoList.length;
            for (var i = 0; i < len; i++) {
                var user = this.userInfoList[i];
                user.isWinner = false;
                user.status = "未完成";
                if (wechatId == user.wechatId) {
                    user.isWinner = true;
                    user.status = "" + seconds + "S";
                }
            }
        };
        PKMatchScene.prototype.addUser = function (userInfo) {
            this.removeUser(userInfo);
            var isFound = false;
            var len = this.userInfoList.length - 1;
            for (var i = len; i >= 0; i--) {
                var roleInfo = this.userInfoList[i];
                if (userInfo.wechatId == roleInfo.wechatId) {
                    roleInfo.status = "准备";
                    roleInfo.isReady = true;
                    isFound = true;
                }
            }
            if (!isFound) {
                this.userInfoList.push(userInfo);
            }
            userInfo.status = "准备";
            userInfo.isReady = true;
            this.updateData();
        };
        PKMatchScene.prototype.removeUser = function (userInfo, isUpdated) {
            if (isUpdated === void 0) { isUpdated = true; }
            var len = this.userInfoList.length - 1;
            for (var i = len; i >= 0; i--) {
                var roleInfo = this.userInfoList[i];
                if (userInfo.wechatId == roleInfo.wechatId) {
                    roleInfo.status = "离开";
                    roleInfo.isReady = false;
                }
            }
            if (isUpdated) {
                this.updateData();
            }
        };
        PKMatchScene.prototype.wxCodeLogin = function () {
            var that = this;
            that.pomelo.request("connector.entryHandler.wxlogin", {
                "code": that.code,
                "appToken": manager.GameManager.getInstance().getAppToken()
            }, function (data) {
                if (data.code == PKMatchScene.OK_CODE) {
                    if (that.isJoin) {
                        that.joinRoom(that.roomId);
                    }
                    else {
                        that.createRoom();
                    }
                }
            });
        };
        //发起准备好的指令
        PKMatchScene.prototype.setReady = function () {
            var that = this;
            that.pomelo.request("game.gameHandler.gameSceneReady", {}, function (data) {
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
        };
        PKMatchScene.prototype.connect = function (host, port) {
            var that = this;
            this.pomelo.init({
                host: host,
                port: port,
                reconnect: true
            }, function () {
                that.isConnected = true;
                that.wxLogin();
            });
        };
        PKMatchScene.prototype.wxLogin = function () {
            var that = this;
            wx.login({
                success: function (res) {
                    if (res.code) {
                        egret.log("获取code1:", res.code);
                        that.code = res.code;
                        // that.wxCodeLogin();
                    }
                    else {
                        console.log('登录失败！' + res.errMsg);
                    }
                },
                fail: function (res) {
                },
                complete: function (res) {
                }
            });
        };
        //加入房间即可准备Ready
        PKMatchScene.prototype.joinRoom = function (roomId) {
            var _this = this;
            egret.log("join room");
            var that = this;
            that.pomelo.request("match.matchHandler.joinRoom", {
                "gameKindId": PKMatchScene.GAME_KIND_ID,
                "roomId": roomId,
            }, function (data) {
                if (data.code == PKMatchScene.OK_CODE) {
                    that.userInfoList = data.userInfoList;
                    that.setPrepare("准备");
                    that.roomInfo = data.roomInfo;
                    that.updateData();
                    that.isJoin = true;
                    that.setInfo(that.isJoin, that.roomInfo.roomId);
                    _this.txtTip.text = "等待房主开始游戏";
                }
                else {
                    that.showCreateRoomTip();
                }
            });
        };
        PKMatchScene.prototype.showCreateRoomTip = function () {
            var that = this;
            wx.showModal({
                title: '提示',
                content: '房间已失效，可自己创建房间',
                confirmText: "创建房间",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        that.createRoom();
                    }
                    else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        };
        //创建房间即可准备Ready
        PKMatchScene.prototype.createRoom = function () {
            var _this = this;
            egret.log("create room");
            var that = this;
            that.pomelo.request("match.matchHandler.createRoom", {
                "gameKindId": PKMatchScene.GAME_KIND_ID,
            }, function (data) {
                if (data.code == PKMatchScene.OK_CODE) {
                    that.reset();
                    that.userInfoList = data.userInfoList;
                    that.setPrepare("准备");
                    that.roomInfo = data.roomInfo;
                    that.isJoin = false;
                    that.updateData();
                    that.setInfo(that.isJoin, that.roomInfo.roomId);
                    that.showFriendModal();
                    _this.txtTip.text = "等待邀请好友来PK";
                }
            });
        };
        PKMatchScene.prototype.setPrepare = function (status) {
            if (status === void 0) { status = "准备"; }
            for (var i = 0; i < this.userInfoList.length; i++) {
                var roleInfo = this.userInfoList[i];
                roleInfo.status = status;
                roleInfo.isReady = true;
            }
        };
        PKMatchScene.prototype.showFriendModal = function () {
            var that = this;
            wx.showModal({
                title: '提示',
                content: '请邀请好友加入',
                confirmText: "邀请好友",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        that.inviteFriend();
                    }
                    else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        };
        PKMatchScene.prototype.leaveRoom = function () {
            egret.log("join room");
            this.sendCustomMessage({
                command: PKMatchScene.LEAVE_ROOM,
                wechatId: manager.GameManager.getInstance().openid,
            });
            this.pomelo.request("match.matchHandler.leaveRoom", {}, function (data) {
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
            this.pomelo.disconnect();
            this.pomelo = null;
        };
        PKMatchScene.SELECT_LEVEL_COMMAND = "game.myHandler.select_level";
        PKMatchScene.SYNC_WIN_SCORE = "SyncWinScore";
        PKMatchScene.REPLAY_GAME = "ReplayGame";
        PKMatchScene.LEAVE_ROOM = "LeaveRoom";
        PKMatchScene.GAME_KIND_ID = 4;
        PKMatchScene.OK_CODE = 200;
        // public static ROUTE_SERVER_HOST: string = "test.pk.2zhuji.cn";
        PKMatchScene.ROUTE_SERVER_HOST = "pk.2zhuji.cn";
        PKMatchScene.ROUTE_SERVER_PORT = 3014;
        return PKMatchScene;
    }(eui.Component));
    scene.PKMatchScene = PKMatchScene;
})(scene || (scene = {}));
